﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoardController.Helper;
using Common.Utils;

namespace BoardController.CommHelp
{
    public class SliderHelp
    {
        private static List<Byte> lisSliderComBytes = new List<byte>();
        static SliderHelp()
        {
            //头
            byte[] head = new byte[3];
            head[0] = 0xAA;
            head[1] = 0x55;
            head[2] = 0xCC;
            //设备地址
            byte dviceAdress = 0x03;
            //功能码 写多寄存器
            byte function = 0x10;
            //寄存器起始地址(13是滑台)
            short adress = 0x13;
            //寄存器数
            short RegsCount = 3;

            lisSliderComBytes.AddRange(head);
            lisSliderComBytes.Add(dviceAdress);
            lisSliderComBytes.Add(function);
            lisSliderComBytes.AddRange(BitConverter.GetBytes(adress).Reverse());
            lisSliderComBytes.AddRange(BitConverter.GetBytes(RegsCount).Reverse());
        }

        public static byte[] SliderMove(short mode, short position, byte speed, byte acc)
        {
            List<byte> lisBytes = new List<byte>();
            lisBytes.AddRange(lisSliderComBytes);
            //数据
            List<byte[]> dateBytes = new List<byte[]>();
            //滑台模式
            dateBytes.Add(BitConverter.GetBytes(mode).Reverse().ToArray()); ;  //01 复位清零 02 速度模式 03 位置模式  04 立即停止
            short sliderMotorControl = 0;
            switch (mode)
            {
                case 0x02:
                    if (position > 0)
                    {
                        sliderMotorControl = 2;//向右
                    }
                    else
                    {
                        sliderMotorControl = 1;//向左
                    }
                    break;
                case 0x03:
                    sliderMotorControl = position;
                    break;
                case 0x04:
                    sliderMotorControl = Math.Abs(sliderMotorControl);
                    break;
                default:
                    break;
            }
            //滑台电机控制参数
            dateBytes.Add(BitConverter.GetBytes(sliderMotorControl).Reverse().ToArray());//1向左 2向右
            //滑台电机运动参数
            dateBytes.Add(new byte[] { speed, acc });//速度200 加速度200
            foreach (byte[] dateByte in dateBytes)
            {
                lisBytes.AddRange(dateByte);
            }
            //标签
            byte[] labelBytes = new byte[] { 4, 0 };
            lisBytes.AddRange(labelBytes);
            var crc = FastCRC.ZaneCRC(lisBytes);
            lisBytes.AddRange(crc);
            return lisBytes.ToArray();
        }
    }
}
